'''
Created on Apr 19, 2009

@author: Administrator
'''
from datetime import datetime

from django.utils.translation import ugettext_lazy as _
from com.ericyang.groupshopping.addressbook.models import AddressBook
from com.ericyang.groupshopping.order.models import GroupOrder, GroupOrderVendor, GroupOrderUser
from django import forms
from com.ericyang.common.web.middleware import threadlocals

# Group Order creation form
class OrderVendorCreationForm(forms.ModelForm):
    '''
    form of order creation
    '''
    has_stored_product = forms.BooleanField(label=_("has stored product"), required=False)

    deliver_type = forms.ChoiceField(label=_("deliver Type"), choices=GroupOrderVendor.DELIVER_TYPE_CHIOSES)
    payment_type = forms.ChoiceField(label=_("payment Type"), choices=GroupOrderVendor.PAYMENT_TYPE_CHIOSES)
    
    class Meta:
         model = GroupOrderVendor
         fields = ("has_stored_product", "deliver_type", 'payment_type')
         
    def __init__(self, order, *args, **kwargs):
        self.order = order
        super(OrderVendorCreationForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        vendor = super(OrderVendorCreationForm, self).save(commit=False)
        vendor.order = self.order
        vendor.status = GroupOrderVendor.STATUS_DEFAULT
        vendor.user = threadlocals.get_current_user()
        if commit:
            vendor.save()
        return vendor

# Group Order creation form
class GroupOrderCreationForm(forms.ModelForm):
    '''
    form of order creation
    '''
    title = forms.CharField(label=_("title"), max_length=200)
    minUserNum = forms.IntegerField(label=_("min user number"), min_value=1)
    maxUserNum = forms.IntegerField(label=_("max user number"), min_value=1)
    minVendorNum = forms.IntegerField(label=_("min vendor number"), min_value=1)
    maxVendorNum = forms.IntegerField(label=_("max vendor number"), min_value=1)
    proposalPrice = forms.DecimalField(label=_("proposal price"), max_digits=12, decimal_places=2)

    deadline = forms.DateField(label=_('dead line'), required=False) 
    
    class Meta:
         model = GroupOrder
         fields = ("title", "minUserNum", 'maxUserNum', 'minVendorNum', 'maxVendorNum', 'proposalPrice', 'deadline')
         
    def __init__(self, product, *args, **kwargs):
        self.product = product
        super(GroupOrderCreationForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        groupOrder = super(GroupOrderCreationForm, self).save(commit=False)
        groupOrder.product = self.product 
        groupOrder.status = GroupOrder.STATUS_CHIOSES[0][0]
        groupOrder.createTime = datetime.now()
        user = threadlocals.get_current_user()
        groupOrder.createUser = user
        
        if commit:
            groupOrder.save()
        
        if user.is_common_user():
            order_user = GroupOrderUser()        
            order_user.order = groupOrder
            try:
                order_user.address_book = AddressBook.objects.filter(user__id=user.id)[0]
                order_user.user = user
                order_user.save()
            except IndexError: 
                print "No address book"
            
        return groupOrder

# Group Order creation form
class GroupOrderChangeForm(forms.ModelForm):
    '''
    form of order creation
    '''
    title = forms.CharField(label=_("title"), max_length=200)
    minUserNum = forms.IntegerField(label=_("min user number"), min_value=1)
    maxUserNum = forms.IntegerField(label=_("max user number"), min_value=1)
    minVendorNum = forms.IntegerField(label=_("min vendor number"), min_value=1)
    maxVendorNum = forms.IntegerField(label=_("max vendor number"), min_value=1)
    proposalPrice = forms.DecimalField(label=_("proposal price"), max_digits=12, decimal_places=2)

    deadline = forms.DateField(label=_('dead line'), required=False) 
    
    class Meta:
         model = GroupOrder
         fields = ("title", "minUserNum", 'maxUserNum', 'minVendorNum', 'maxVendorNum', 'proposalPrice', 'deadline')
         
    def __init__(self, groupOrder, *args, **kwargs):
        self.groupOrder = groupOrder
        
        # if not args then it's not POST.
        if not args:
            order_args = {'minUserNum':groupOrder.minUserNum,
                            'maxUserNum':groupOrder.maxUserNum,
                            'minVendorNum':groupOrder.minVendorNum,
                            'maxVendorNum':groupOrder.maxVendorNum,
                            'proposalPrice':groupOrder.proposalPrice,
                            'deadline':groupOrder.deadline,
                            }
            super(GroupOrderChangeForm, self).__init__(order_args, **kwargs)
        else:
            super(GroupOrderChangeForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        self.groupOrder.minUserNum = self.cleaned_data['minUserNum']
        self.groupOrder.maxUserNum = self.cleaned_data['maxUserNum']
        self.groupOrder.minVendorNum = self.cleaned_data['minVendorNum']
        self.groupOrder.maxVendorNum = self.cleaned_data['maxVendorNum']
        self.groupOrder.proposalPrice = self.cleaned_data['proposalPrice']
        self.groupOrder.deadline = self.cleaned_data['deadline']

        if commit:
            self.groupOrder.save()
        return self.groupOrder
    